package com.cardbaobao.cardbabyclient.model.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.cardbaobao.cardbabyclient.model.database.CbbDataBase;
import com.cardbaobao.cardbabyclient.model.database.SQL;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jiangzx on 2017/7/6 18:59.
 */

public class HaveReadMessageDao {
    /**已读消息 表名*/
    private static final String TABLE_NAME=SQL.TABLE_HAVE_READ_MESSAGE;
    /**点赞信息 字段 id*/
    private static final String KEY_ID="id";

    private SQLiteDatabase mDataBase;

    public HaveReadMessageDao(){
        init();
    }

    private synchronized SQLiteDatabase init(){
        CbbDataBase dataBaseHelper=
                new CbbDataBase(ApplicationHelper.getApplicationContext(),
                        SQL.DB_NAME,null,SQL.DB_VERSION);
        if(mDataBase==null||!mDataBase.isOpen()){
            mDataBase=dataBaseHelper.getWritableDatabase();
        }
        return mDataBase;
    }

    private void closeDateBase(){
        if(null!=mDataBase){
            mDataBase.close();
            mDataBase=null;
        }
    }

    /***
     * 获取所有已读消息的id
     */
    public List<Long> getAllHaveReadMessage(){
        init();
        List<Long> list=new ArrayList<>();
        Cursor cursor=mDataBase.query(TABLE_NAME,new String[]{KEY_ID},null,null,null,null,null);
        if(cursor!=null){
            if(cursor.moveToFirst()){
                for(int i=0,size=cursor.getCount();i<size;i++){
                    list.add(cursor.getLong(cursor.getColumnIndex(KEY_ID)));
                    cursor.moveToNext();
                }
            }
            cursor.close();
        }
        closeDateBase();
        return list;
    }

    /**批量插入已读消息id*/
    public boolean insertHaveReadMessages(List<Long> messageIds){
        if(messageIds==null||messageIds.size()==0){
            return false;
        }
        init();
        mDataBase.beginTransaction();
        for(Long i:messageIds){
            ContentValues values=new ContentValues(1);
            values.put(KEY_ID,i);
            mDataBase.insert(TABLE_NAME,null,values);
        }
        mDataBase.setTransactionSuccessful();
        mDataBase.endTransaction();
        closeDateBase();
        return true;
    }

    /**清除所有的已读消息*/
    public boolean clearHaveReadMessages(){
        init();
        mDataBase.delete(TABLE_NAME,null,null);
        closeDateBase();
        return true;
    }
}
